44. Dynamic Parameters

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

44.1: "Simple" dynamic parameter

This example adds a new parameter to MyTestFunction if $SomeUsefulNumber is greater than 5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function MyTestFunction
{
  [CmdletBinding(DefaultParameterSetName = 'DefaultConfiguration')]
  Param
  (
    [Parameter(Mandatory = $true)][int]$SomeUsefulNumber
  )
  DynamicParam
  {
    $paramDictionary = New-Object -TypeName
    System.Management.Automation.RuntimeDefinedParameterDictionary
    $attributes = New-Object -TypeName System.Management.Automation.ParameterAttribute
    $attributes.ParameterSetName = '__AllParameterSets'
    $attributes.Mandatory = $true
    $attributeCollection = New-Object -TypeName
    System.Collections.ObjectModel.Collection[System.Attribute]
    $attributeCollection.Add($attributes)
    # If "SomeUsefulNumber" is greater than 5, then add the "MandatoryParam1" parameter
    if($SomeUsefulNumber -gt 5)
    {
      # Create a mandatory string parameter called "MandatoryParam1"
      $dynParam1 = New-Object -TypeName
      System.Management.Automation.RuntimeDefinedParameter('MandatoryParam1', [String], 
      $attributeCollection)
      # Add the new parameter to the dictionary
      $paramDictionary.Add('MandatoryParam1', $dynParam1)
    }
    return $paramDictionary
  }
  process
  {
    Write-Host -Object "SomeUsefulNumber = $SomeUsefulNumber"
    # Notice that dynamic parameters need a specific syntax
    Write-Host -Object ('MandatoryParam1 = {0}' -f $PSBoundParameters.MandatoryParam1)
  }
}

Usage:

1
2
3
MyTestFunction -SomeUsefulNumber 3
SomeUsefulNumber = 3
MandatoryParam1 =
1
2
3
4
MyTestFunction -SomeUsefulNumber 6
cmdlet MyTestFunction at command pipeline position 1
Supply values for the following parameters:
MandatoryParam1:
1
2
3
MyTestFunction -SomeUsefulNumber 6 - MandatoryParam1 test
SomeUsefulNumber = 6
MandatoryParam1 = test

In the second usage example, you can clearly see that a parameter is missing.

Dynamic parameters are also taken into account with auto completion. Here's what happens if you hit ctrl + space at the end of the line:

1
2
3
4
MyTestFunction -SomeUsefulNumber 3 -<ctrl+space>
Verbose WarningAction WarningVariable OutBuffer
Debug InformationAction InformationVariable PipelineVariable
ErrorAction ErrorVariable OutVariable
1
2
3
4
MyTestFunction -SomeUsefulNumber 6 -<ctrl+space>
MandatoryParam1 ErrorAction ErrorVariable OutVariable
Verbose WarningAction WarningVariable OutBuffer
Debug InformationAction InformationVariable PipelineVariable